package com.apes.project.jekunAuto.report.service;


import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.connector.http.HttpTransporter;
import com.apes.framework.util.MD5Util;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.PropertiesUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 功能：报表服务
 *
 * @author xul
 * @create 2018-05-03 9:55
 */
@Service("reportService")
public class ReportService extends DomainService {

    static String appid = "yyesb";
    static String secretKey = "h2B1UfmJ";

    @Autowired
    PropertiesUtils propertiesUtils;

    @Value("${yyerp.url}")
    public String url;

    public String interfaceData(SimpleRequest request) {

        Map data = new HashMap();
        data.put("pdata", request.get("pdata"));

        Map headers = new HashMap();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        headers.putAll(calcPassword());
        System.out.println("URL:"+url);

        headers.put("method", request.get("interfaceMethod"));

        HttpTransporter transporter = new HttpTransporter();
        transporter.setUrl("{{yyerp.url}}");
        transporter.setHeaders(headers);

        SimpleRequest rqst = new SimpleRequest();
        rqst.setData(data);
        return (String) transporter.process(rqst);
    }

    public String sendDataToApp(Map<String, Object> data, String sMethod) throws Exception {
        JSONObject json = new JSONObject();        //json用来拼接调用地址
        json.put("URL",propertiesUtils.getProperty("interface.access_url"));
        String sUrl = json.getString("URL") + "/" + sMethod;

        Map headers = getAPPHeaders("POST", sMethod, data.toString().length());

        HttpTransporter transporter = new HttpTransporter();
        transporter.setUrl(sUrl);
        transporter.setHeaders(headers);

        SimpleRequest rqst = new SimpleRequest();
        //rqst.setData(data);

        List<FormBodyPart> parts = new ArrayList();
        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
        data.forEach((k,v) -> {
            parts.add(FormBodyPartBuilder.create(k, new StringBody(String.valueOf(v), contentType)).build());
        });
        rqst.setData(parts.toArray(new FormBodyPart[parts.size()]));

        return (String) transporter.process(rqst);
    }



    /**
     * 获取App接口的头信息，秘钥相关的字段
     *
     * @param action
     * @param sMethod
     * @param length
     * @return
     * @throws Exception
     */
    public Map<String, Object> getAPPHeaders(String action, String sMethod, int length) throws Exception {
        String access_key = propertiesUtils.getProperty("interface.access_key");
        String access_id = propertiesUtils.getProperty("interface.access_id");
        Calendar calendar = Calendar.getInstance();
        //calendar.add(calendar.HOUR, -8);
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT  hjl 2017-05-21
        String time = sdf.format(date);
        String Signature = action + "\\n" + sMethod + "\\n" + length + "\\n" + time;
        //构造密钥: 第一个参数---字节数组(access_key为密钥),第二参数----一个密钥算法的名称

        SecretKeySpec keySpec = new SecretKeySpec(access_key.getBytes("UTF-8"), "HmacSHA1"); //NBsV-7b-ubJuBAPf	NAsV-7b-ubJuBAPg
        //生成一个指定MAC算法的mac对象
        Mac mac = Mac.getInstance("HmacSHA1");
        //用给定密钥初始化 mac 对象
        mac.init(keySpec);
        //使用 HMAC-SHA1 签名方法对对Signature进行签名 ,完成 Mac 操作
        String text = com.alibaba.druid.util.Base64.byteArrayToBase64(mac.doFinal(Signature.getBytes("UTF-8")));
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("Authorization", access_id + ":" + text);//18028603027
        headers.put("Date", time);
        headers.put("Entity-Length", String.valueOf(length));
//        headers.put("from","18028603027");
//        headers.put("Content-Type", "application/x-www-form-urlencoded");
        return headers;
    }


    /***
     * 计算连接yyerp的password
     * 1. 获取去除后三位的当前时间戳
     * 2. 利用密钥和当前时间戳连接并进行MD5加密
     * 3. 取加密后的前八位
     * @return
     */
    private Map calcPassword(){
        String time = String.valueOf(System.currentTimeMillis());
        time = time.substring(0,time.length() - 3);
        String password = MD5Util.encrypt(appid + secretKey + time).substring(0,8);
        return MapUtil.mapper("time", time, "pass", password, "appid", appid);
    }
}
